//
//  ShortVideoViewController.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/8.
//

import UIKit
import AVFoundation
import SystemConfiguration

// MARK: - 数据模型
struct VideoItem {
    let videoUrl: URL
    var isCached: Bool = false
    var localURL: URL?
}

class ShortVideoViewController: BaseViewController {
    
    // MARK: - 属性
    private var collectionView: UICollectionView!
    private var videoItems: [VideoItem] = []
    private var networkMonitor: NetworkMonitor!
    private var performanceMonitor: PerformanceMonitor!
    
    // MARK: - 生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupPerformanceMonitoring()
        setupNetworkMonitoring()
        loadVideos()
        addNotifications()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        networkMonitor.startMonitoring()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        networkMonitor.stopMonitoring()
    }
    
    // MARK: - 初始化
    private func setupPerformanceMonitoring() {
        performanceMonitor = PerformanceMonitor()
        performanceMonitor.delegate = self
    }
    
    private func setupNetworkMonitoring() {
        networkMonitor = NetworkMonitor.shared
        networkMonitor.delegate = self
    }
    
    // MARK: - UI设置
    private func setupUI() {
        view.theme_backgroundColor = "Colors.black"
        
        // 创建集合视图布局
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = view.bounds.size
        
        // 创建集合视图
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.theme_backgroundColor = "Colors.black"
        collectionView.register(VideoPlayerCell.self, forCellWithReuseIdentifier: VideoPlayerCell.identifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        view.addSubview(collectionView)
        
        // 添加旋转按钮
        let rotationButton = UIButton(type: .custom)
        rotationButton.setImage(UIImage(systemName: "arrow.clockwise"), for: .normal)
        rotationButton.theme_tintColor = "Colors.white"
        rotationButton.theme_backgroundColor = "Colors.black"
        rotationButton.layer.cornerRadius = 25
        rotationButton.addTarget(self, action: #selector(toggleOrientation), for: .touchUpInside)
        view.addSubview(rotationButton)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        rotationButton.snp.makeConstraints { make in
            make.top.right.equalToSuperview().inset(16)
            make.size.equalTo(CGSize(width: 50, height: 50))
        }
        
        // 添加网络状态指示器
        let networkIndicator = UILabel(frame: CGRect(x: 20, y: 50, width: 120, height: 30))
        networkIndicator.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        networkIndicator.textColor = .white
        networkIndicator.textAlignment = .center
        networkIndicator.layer.cornerRadius = 8
        networkIndicator.clipsToBounds = true
        networkIndicator.tag = 100
        networkIndicator.isHidden = true
        view.addSubview(networkIndicator)
    }
    
    // MARK: - 数据加载
    private func loadVideos() {
        // 模拟视频数据
        videoItems = [
            VideoItem(videoUrl: URL(string: "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0200ff00000bdkpfpdd2r6fb5kf6m50&line=0.mp4")!),
            VideoItem(videoUrl: URL(string: "https://lf3-static.bytednsdoc.com/obj/eden-cn/ild_jw_upfbvk_lm/ljhwZthlaukjlkulzlp/download/douyin_pc_client.mp4")!),
            VideoItem(videoUrl: URL(string: "https://www.w3schools.com/html/movie.mp4")!),
            VideoItem(videoUrl: URL(string: "https://www.w3school.com.cn/example/html5/mov_bbb.mp4")!),
            VideoItem(videoUrl: URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!)
        ]
        
        // 优先加载本地缓存
        VideoCacheManager.shared.loadCachedVideos(for: videoItems) { [weak self] cachedItems in
            DispatchQueue.main.async {
                for (index, item) in self?.videoItems.enumerated() ?? [].enumerated() {
                    if let cachedItem = cachedItems[item.videoUrl] {
                        self?.videoItems[index] = cachedItem
                    }
                }
                self?.collectionView.reloadData()
            }
        }
        
        // 初始预加载
        VideoPreloader.shared.preloadVideos(videoItems)
    }
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(appDidEnterBackground),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(appWillEnterForeground),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
    }

}

@objc extension ShortVideoViewController {
    /// 转场进入横屏页面
    func toggleOrientation() {
        
    }
    
    // 暂停播放？
    func appDidEnterBackground() {
        xlog("应用进入后台")
        for cell in collectionView.visibleCells {
            if let videoCell = cell as? VideoPlayerCell {
                videoCell.pause()
            }
        }
    }

    // 恢复播放？
    func appWillEnterForeground() {
        xlog("应用即将进入前台")
    }

}

// MARK: - UICollectionView 数据源和代理
extension ShortVideoViewController: UICollectionViewDataSource,
                                    UICollectionViewDelegate,
                                    UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.frame.size
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return videoItems.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VideoPlayerCell.identifier, for: indexPath) as! VideoPlayerCell
        cell.configure(with: videoItems[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let videoCell = cell as? VideoPlayerCell {
            videoCell.play()
        }
        
        // 动态预加载策略
        let preloadIndices = VideoPreloader.shared.calculatePreloadIndices(
            currentIndex: indexPath.item,
            totalCount: videoItems.count,
            networkType: networkMonitor.currentNetworkType
        )
        
        for index in preloadIndices {
            VideoPreloader.shared.preloadVideo(videoItems[index])
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let videoCell = cell as? VideoPlayerCell {
            videoCell.pause()
        }
    }
}

extension ShortVideoViewController: PerformanceMonitorDelegate {
    func performanceWarning(category: String, message: String) {
        print("[Performance Warning] \(category): \(message)")
        
        // 在实际应用中，这里应该记录到日志系统
        // 对于严重问题，可以触发清理操作
        if category == "Memory" {
            VideoPreloader.shared.clearCache()
            VideoCacheManager.shared.cleanCacheIfNeeded()
        }
    }
}

// MARK: - 扩展和工具方法
extension ShortVideoViewController: NetworkMonitorDelegate {
    func networkStatusChanged(type: NetworkType) {
        guard let indicator = view.viewWithTag(100) as? UILabel else { return }
        
        switch type {
        case .wifi:
            indicator.text = "WiFi"
            indicator.backgroundColor = .systemGreen
        case .cellular:
            indicator.text = "4G/5G"
            indicator.backgroundColor = .systemOrange
        case .unknown:
            indicator.text = "无网络"
            indicator.backgroundColor = .systemRed
        }
        
        // 显示网络状态指示器
        indicator.isHidden = false
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            UIView.animate(withDuration: 0.5) {
                indicator.isHidden = true
            }
        }
        
        // 更新预加载策略
        VideoPreloader.shared.clearCache()
    }
}
